package com.bookshop.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.bookshop.entity.response.TokenEnum;

import java.util.Date;

/**
 * @author g2l
 * @create 2022-07-26 17:35
 */
public class JWTUtil {
    private static final String SECRET_KEY = "123456"; // 秘钥  加密token用的
    private static final long TOKEN_EXPIRE_TIME = 60 * 60 * 1000; // token过期时间，单位ms，这里是1h
    // refreshToken过期时间，这里是12h
    private static final long REFRESH_EXPIRE_TIME = 12 * 60 * 60 * 1000;
    private static final String ISSUER = "g2l"; // 签发人

    /**
     * 生成签名
     */
    public static String generateToken(String username){
        Date now = new Date();
        // 创建签名算法对象
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);// 算法

        String token = JWT.create()
                .withIssuer(ISSUER) // 签发人
                .withIssuedAt(now) // 签发时间
                .withExpiresAt(new Date(now.getTime() + TOKEN_EXPIRE_TIME)) // 过期时间
                .withClaim("username",username) // 保存身份标识
                .sign(algorithm);
        return token;
    }

    /**
     * 生成签名
     */
    public static String generateRefreshToken(String username){
        Date now = new Date();
        // 创建签名算法对象
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);// 算法

        String token = JWT.create()
                .withIssuer(ISSUER) // 签发人
                .withIssuedAt(now) // 签发时间
                .withExpiresAt(new Date(now.getTime() + REFRESH_EXPIRE_TIME)) // 过期时间
                .withClaim("username",username) // 保存身份标识
                .sign(algorithm);
        return token;
    }

    /**
     * 验证token
     */
    public static TokenEnum verify(String token) {
        try {
            // 签名算法
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);// 算法
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(ISSUER)
                    .build();

            verifier.verify(token);
            return TokenEnum.TOKEN_SUCCESS;
        } catch (TokenExpiredException e) {
            return TokenEnum.TOKEN_EXPIRE;
        } catch (JWTVerificationException e) {
            return TokenEnum.TOKEN_BAD;
        }
    }
        /**
         * 从token中获取username
         */
        public static String getUsername(String token){
            try {
                return JWT.decode(token).getClaim("username").asString();
            } catch (JWTDecodeException e) {
                e.printStackTrace();
            }
            return "";
        }

}